<?php

namespace Gds\VenteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Gds\VenteBundle\Entity\Client;
use Gds\VenteBundle\Form\ClientType;
use JMS\SecurityExtraBundle\Annotation\Secure;

class ClientController extends Controller {

    /**
     * @Secure(roles="ROLE_CLIENT_CRUD")
     */
    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $dql = "SELECT c FROM GdsVenteBundle:Client c WHERE (c.is_active=:is_active and c.raison_social LIKE :raison_social and c.code LIKE :code )";
        $query = $em->createQuery($dql)->setParameters(array('is_active' => true, 'raison_social' => '%' . $request->get('raison_social') . '%', 'code' => '%' . $request->get('code') . '%'));
        $paginator = $this->get('knp_paginator');

        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );
        if ($request->get('type')) {
            return $this->render('GdsVenteBundle:Client:pageList.html.twig', array('pagination' => $pagination));
        }
        return $this->render('GdsVenteBundle:Client:index.html.twig', array('pagination' => $pagination));
    }

    /**
     * @Secure(roles="ROLE_CLIENT_CRUD")
     */
    public function listAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $dql = "SELECT c FROM GdsVenteBundle:Client c WHERE (c.is_active=:is_active and c.raison_social LIKE :raison_social and c.code LIKE :code )";


        $query = $em->createQuery($dql)->setParameters(array('is_active' => true, 'raison_social' => '%' . $request->get('raison_social') . '%', 'code' => '%' . $request->get('code') . '%'));
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );
        if ($request->get('type')) {
            return $this->render('GdsVenteBundle:Client:pageList.html.twig', array('pagination' => $pagination));
        }
        return $this->render('GdsVenteBundle:Client:list.html.twig', array('pagination' => $pagination));
    }

    public function newForBlAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        try {
            $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
            $raison_social = $request->get('raison_social');
            $matricule = $request->get('matricule');
            $adresse = $request->get('adresse');
            $gsm = $request->get('gsm');
            $client = new Client();
            $client->setCode($societe->getPrefixeClient() . "-" . sprintf("%04s", $societe->getNumeroClient() + 1));
            $client->setAdresse($adresse);
            $client->setGsm($gsm);  
            $client->setLimiteCredit(0);
            $client->setSolde(0);
            $client->setRaisonSocial($raison_social);
            $client->setMatriculeFiscale($matricule);
            $em->persist($client);
            $societe->setNumeroClient($societe->getNumeroClient() + 1);
            $em->flush();
            $id = $client->getId();
        } catch (Exception $ex) {
            $response = new Response(json_encode(array('success' => false)));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        $response = new Response(json_encode(array('success' => true, 'id' => $id)));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    /**
     * @Secure(roles="ROLE_CLIENT_CRUD")
     */
    public function newAction() {
        $client = new Client();
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll();
        $client->setCode($societe[0]->getPrefixeClient() . "-" . sprintf("%04s", $societe[0]->getNumeroClient() + 1));
        $client->setSolde(number_format(0, 3));
        $client->setLimiteCredit($societe[0]->getLimiteCredit());
        $form = $this->createForm(new ClientType(), $client);
        if ($request->isMethod('post')) {
            $form->bind($request);
            if ($form->isValid()) {
                $client = $form->getData();
                $client->setCode($societe[0]->getPrefixeClient() . "-" . sprintf("%04s", $societe[0]->getNumeroClient() + 1));
                $societe[0]->setNumeroClient($societe[0]->getNumeroClient() + 1);
                $em->persist($societe[0]);
                $em->persist($client);
                $em->flush();
                $red = $request->get('red');
                if ($red == 'n') {
                    $client = new Client();
                    $client->setCode($societe[0]->getPrefixeClient() . "-" . sprintf("%04s", $societe[0]->getNumeroClient() + 1));
                    $client->setSolde(number_format(0, 3));
                    $client->setLimiteCredit($societe[0]->getLimiteCredit());
                    $form = $this->createForm(new ClientType(), $client);
                    return $this->render('GdsVenteBundle:Client:new.html.twig', array('form' => $form->createView()));
                } else {
                    $em = $this->getDoctrine()->getEntityManager();
                    $request = $this->getRequest();
                    $dql = "SELECT c FROM GdsVenteBundle:Client c WHERE (c.is_active=:is_active and c.raison_social LIKE :raison_social and c.code LIKE :code )";


                    $query = $em->createQuery($dql)->setParameters(array('is_active' => true, 'raison_social' => '%' . $request->get('raison_social') . '%', 'code' => '%' . $request->get('code') . '%'));
                    $paginator = $this->get('knp_paginator');
                    $pagination = $paginator->paginate(
                            $query, $request->get('page', 1)/* page number */, 10/* limit per page */
                    );
                    $pagination->setUsedRoute('gds_client_list');
                    if ($request->get('type')) {
                        return $this->render('GdsVenteBundle:Client:pageList.html.twig', array('pagination' => $pagination));
                    }
                    return $this->render('GdsVenteBundle:Client:list.html.twig', array('pagination' => $pagination));
                }
            }
        }
        return $this->render('GdsVenteBundle:Client:new.html.twig', array('form' => $form->createView()));
    }

    public function editAction() {

        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($id);
        $form = $this->createForm(new ClientType(), $client);

        if ($request->isMethod('post')) {
            $form->bind($request);
            $client = $form->getData();
            $em->persist($client);
            $em->flush();
            $red = $request->get('red');
            if ($red == 'n') {
                $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll();
                $client = new Client();
                $client->setCode($societe[0]->getPrefixeClient() . "-" . sprintf("%04s", $societe[0]->getNumeroClient() + 1));
                $client->setSolde(number_format(0, 3));
                $client->setLimiteCredit($societe[0]->getLimiteCredit());
                $form = $this->createForm(new ClientType(), $client);
                return $this->render('GdsVenteBundle:Client:new.html.twig', array('form' => $form->createView()));
            } else {
                $em = $this->getDoctrine()->getEntityManager();
                $request = $this->getRequest();
                $dql = "SELECT c FROM GdsVenteBundle:Client c WHERE (c.is_active=:is_active and c.raison_social LIKE :raison_social and c.code LIKE :code )";
                $query = $em->createQuery($dql)->setParameters(array('is_active' => true, 'raison_social' => '%' . $request->get('raison_social') . '%', 'code' => '%' . $request->get('code') . '%'));
                $paginator = $this->get('knp_paginator');
                $pagination = $paginator->paginate(
                        $query, $request->get('page', 1)/* page number */, 10/* limit per page */
                );
                $pagination->setUsedRoute('gds_client_list');
                if ($request->get('type')) {
                    return $this->render('GdsVenteBundle:Client:pageList.html.twig', array('pagination' => $pagination));
                }
                return $this->render('GdsVenteBundle:Client:list.html.twig', array('pagination' => $pagination));
            }
        }
        return $this->render('GdsVenteBundle:Client:edit.html.twig', array('form' => $form->createView(), 'id' => $id));
    }

    /**
     * @Secure(roles="ROLE_CLIENT_DELETE")
     */
    public function deleteAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($id);
        $client->setIsActive(false);
        $em->persist($client);
        $em->flush();
        $dql = "SELECT c FROM GdsVenteBundle:Client c WHERE (c.is_active=:is_active and c.raison_social LIKE :raison_social and c.code LIKE :code )";
        $query = $em->createQuery($dql)->setParameters(array('is_active' => true, 'raison_social' => '%' . $request->get('raison_social') . '%', 'code' => '%' . $request->get('code') . '%'));
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );
        $pagination->setUsedRoute('gds_client_list');
        if ($request->get('type')) {
            return $this->render('GdsVenteBundle:Client:pageList.html.twig', array('pagination' => $pagination));
        }
        return $this->render('GdsVenteBundle:Client:list.html.twig', array('pagination' => $pagination));
    }

    public function getAllClientSelectAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $clients = $em->getRepository('GdsVenteBundle:Client')->findAll();
        $rows = array();
        foreach ($clients as $client) {
            $tab = array();
            $tab['id'] = $client->getId();
            $tab['raison_social'] = $client->getRaisonSocial();
            $tab['name'] = $client->getRaisonSocial() . ':' . $client->getNom() . ' ' . $client->getPrenom();
            $tab['code'] = $client->getCode();
            $tab['code_barre'] = $client->getCodeBarre();
            $tab['limite_credit'] = $client->getLimiteCredit();
            $tab['solde'] = $client->getSolde();
            $rows[] = $tab;
        }
        $response = new Response(json_encode($rows));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getAllClientAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $clients = $em->getRepository('GdsVenteBundle:Client')->findAll();
        return $this->render('GdsVenteBundle:Client:client.html.twig', array('clients' => $clients));
    }

}
